package com.atguigu.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.gulimall.product.service.CategoryBrandRelationService;
import com.atguigu.gulimall.product.vo.Catelog2Vo;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private RedissonClient redissonClient;
//    private Map<String, Object> cache = new HashMap<String, Object>();

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        // 1、查出所有分类
        List<CategoryEntity> categoryEntityList = this.baseMapper.selectList(null);
        // 2、组装成父子的树形结构
        // 2.1、先找到所有的一级分类
        List<CategoryEntity> levelFirstMenuListcollected = categoryEntityList.stream().filter((categoryEntity) -> {
            return categoryEntity.getParentCid() == 0;
        }).map((menu) -> {
            menu.setChildren(getChildren(menu, categoryEntityList));
            return menu;
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());

        return levelFirstMenuListcollected;
    }

    /**
     * 从所有菜单列表中找出对应菜单的子菜单（递归查找）
     * @param categoryEntity    给出的目标上级菜单
     * @param categoryEntityList    所有菜单列表
     * @return
     */
    private List<CategoryEntity> getChildren(CategoryEntity categoryEntity, List<CategoryEntity> categoryEntityList) {

        List<CategoryEntity> childrenCategoryList = categoryEntityList.stream().filter((categoryEntity1) -> {
            return categoryEntity1.getParentCid() == categoryEntity.getCatId();
        }).map((categoryEntity1) -> {
            // 递归查找子菜单
            categoryEntity1.setChildren(getChildren(categoryEntity1, categoryEntityList));
            return categoryEntity1;
        }).sorted((menu1, menu2) -> {
            // 菜单排序
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());

        return childrenCategoryList;
    }

    @Override
    public void removeMenuByIdList(List<Long> asList) {
        // TODO: 检查当前要删除的菜单是否被其他地方引用
        // 逻辑删除
        this.baseMapper.deleteBatchIds(asList);
    }

    @Override
    public Long[] findCatelogPath(Long catelogId) {

        List<Long> longList = new ArrayList<>();
        List<Long> parentPathList = this.findParentPath(catelogId, longList);
        Collections.reverse(parentPathList);
        return parentPathList.toArray(new Long[parentPathList.size()]);
    }

    private List<Long> findParentPath(Long catelogId, List<Long> pathList) {

        pathList.add(catelogId);
        CategoryEntity byId = this.getById(catelogId);
        if (byId.getParentCid() != 0) {
            this.findParentPath(byId.getParentCid(), pathList);
        }
        return pathList;
    }

    /**
     * 级联更新所有关联的数据
     * @param category
     */
//    @Caching(evict = {      // 同时进行多种缓存操作
//            @CacheEvict(value = "category", key = "'getLevel1Categorys'"),
//            @CacheEvict(value = "category", key = "'getCatalogJson'")
//    })
    @Override
    @Transactional
    @CacheEvict(value = "category", allEntries = true)      // 失效模式：删除该缓存分区下的所有key数据
    public void updateCascade(CategoryEntity category) {

        this.updateById(category);
        this.categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());
        // 同时修改缓存中的数据
    }

    // 每一个需要缓存的数据都来指定要放到哪个名字的缓存【相当于指定缓存的分区（按照业务类型分）】
    // 代表当前方法的结果需要缓存, 如果缓存中有，方法不用调用，如果缓存中没有，会调用方法，最后将方法的结果放入缓存
    /**默认行为：
     * 1）如果缓存中有，方法不用调用
     * 2）key默认自动生成，缓存的名字SimpleKey【】（自主生成的key值）
     * 3）缓存的value的值，默认使用jdk序列化机制，将序列化后的数据存到redis
     * 4）默认时间：-1
     *
     * 自定义：
     * 1）指定生成的缓存使用的key：key属性指定，接收一个SpEL
     * 2）指定缓存的数据的存活时间：配置文件中修改ttl
     * 3）将数据保存为json格式
     */
    @Override
    @Cacheable(value = {"category"}, key = "#root.method.name", sync = true)
    public List<CategoryEntity> getLevel1Categorys() {

        System.out.println("----getLevel1Categorys----");
//        long l = System.currentTimeMillis();
        List<CategoryEntity> categoryEntities = this.baseMapper.selectList(new QueryWrapper<CategoryEntity>()
                .eq("parent_cid", 0));
        // --求助IT手艺人
//        for (CategoryEntity categoryEntity : categoryEntities) {
//            List<CategoryEntity> children = this.getChildren(categoryEntity, this.baseMapper.selectList(new QueryWrapper<CategoryEntity>()));
//            categoryEntity.setChildren(children);
//        }
        // 求助IT手艺人--
//        System.out.println("消耗时间：" + (System.currentTimeMillis() - l));
        return categoryEntities;
    }

    /**
     * 从数据库查询并封装业务逻辑
     * @return
     */
    public Map<String, List<Catelog2Vo>> getCatalogJsonFromDBWithLocalLock() {

        synchronized (this) {
            return getDataFromDB();
        }
    }

    private Map<String, List<Catelog2Vo>> getDataFromDB() {

        String catalogJSON = this.redisTemplate.opsForValue().get("catalogJSON");
        if (!StringUtils.isEmpty(catalogJSON)) {
            Map<String, List<Catelog2Vo>> result = JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<Catelog2Vo>>>() {});
            return result;
        }
        System.out.println("----查询了数据库----");
        /**
         * 1、将数据库的多次查询变为一次
         */
        List<CategoryEntity> selectList = this.baseMapper.selectList(new QueryWrapper<>(null));
        // 1、查出所有一级分类
        List<CategoryEntity> level1Categorys = this.getParent_cid(selectList, 0L);
        // 2、封装数据
        Map<String, List<Catelog2Vo>> parent_cid = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), (v) -> {
            // 1、遍历的是所有的一级分类，要查到这个一级分类的二级分类
            List<CategoryEntity> categoryEntities = getParent_cid(selectList, v.getCatId());
            // 2、封装上面的结果
            List<Catelog2Vo> catelog2Vos = null;
            if (categoryEntities != null && categoryEntities.size() > 0) {
                catelog2Vos = categoryEntities.stream().map((l2) -> {
                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                    // 1、找当前二级分类的三级分类封装成vo
                    List<CategoryEntity> level3Catelog = getParent_cid(selectList, l2.getCatId());

                    if (level3Catelog != null && level3Catelog.size() > 0) {
                        List<Catelog2Vo.Catelog3Vo> collect = level3Catelog.stream().map((l3) -> {
                            // 2、封装成指定格式
                            Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                            return catelog3Vo;
                        }).collect(Collectors.toList());

                        catelog2Vo.setCatalog3List(collect);
                    }
                    return catelog2Vo;
                }).collect(Collectors.toList());
            }
            return catelog2Vos;
        }));
        // 将查到的数据放入缓存，将数据先转为json
        this.redisTemplate.opsForValue().set("catalogJSON", JSON.toJSONString(parent_cid), 1, TimeUnit.DAYS);

        return parent_cid;
    }

    private List<CategoryEntity> getParent_cid(List<CategoryEntity> selectList, Long parent_cid) {

        List<CategoryEntity> collect = selectList.stream().filter(item -> item.getParentCid() == parent_cid).collect(Collectors.toList());
        return collect;
//        return this.baseMapper.selectList(new QueryWrapper<CategoryEntity>()
//                        .eq("parent_cid", v.getCatId()));
    }

    // TODO:产生堆外内存溢出异常：OutOfDirectMemoryError
//    @Override
    public Map<String, List<Catelog2Vo>> getCatalogJson2() {
        // 1、加入缓存逻辑
        String catalogJSON = this.redisTemplate.opsForValue().get("catalogJSON");
        if (StringUtils.isEmpty(catalogJSON)) {
            // 缓存中查不到数据，查询数据库
            System.out.println("----缓存没命中，查询数据库----");
            Map<String, List<Catelog2Vo>> catalogJsonFromDB = this.getCatalogJsonFromDBWithRedisLock();
            return catalogJsonFromDB;
        }
        System.out.println("----缓存命中，直接返回----");
        Map<String, List<Catelog2Vo>> result = JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<Catelog2Vo>>>() {});
        return result;
    }

    public Map<String, List<Catelog2Vo>> getCatalogJsonFromDBWithRedisLock() {
        // 1、抢占分布式锁
        String uuid = UUID.randomUUID().toString();
        Boolean lock = this.redisTemplate.opsForValue().setIfAbsent("lock", uuid, 300, TimeUnit.SECONDS);
        if (lock) {
            System.out.println("----获取分布式锁成功----");
            Map<String, List<Catelog2Vo>> dataFromDB;
            try {
                // 加锁成功----执行业务
                // 设置过期时间和加锁，这两个操作必须是同步的，原子性
//            this.redisTemplate.expire("lock", 30, TimeUnit.SECONDS);
                dataFromDB = this.getDataFromDB();
            } finally {
                // 获取值对比+对比成功删除=原子操作    lua脚本解锁
//            String lockValue = this.redisTemplate.opsForValue().get("lock");
//            if (uuid.equals(lockValue)) {
//                // 把自己线程的锁删除，确保是删除自己的锁而不是后面线程的锁
//                this.redisTemplate.delete("lock");
//            }
                String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
                // lua脚本删除锁，具有原子性
                Long lock1 = this.redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList("lock"), uuid);
            }
            return dataFromDB;
        } else {
            System.out.println("----获取分布式锁失败，等待重试----");
            try {
                Thread.sleep(200);
            } catch (Exception e) {}
            // 加锁失败，通过自旋的方式进行重试
            return this.getCatalogJsonFromDBWithRedisLock();
        }
    }

    /**
     * 缓存中的数据如何与数据库中的保持一致
     * @return
     */
    public Map<String, List<Catelog2Vo>> getCatalogJsonFromDBWithRedissonLock() {
        // 1、锁的名字。锁的粒度，越细越快
        // 锁的粒度：具体缓存的是某个数据，11号商品：product-11-lock
        RLock lock = this.redissonClient.getLock("catalogJson-lock");
        lock.lock();

        Map<String, List<Catelog2Vo>> dataFromDB;
        try {
            dataFromDB = this.getDataFromDB();
        } finally {
            lock.unlock();
        }
        return dataFromDB;
    }

    @Override
    @Cacheable(value = "category", key = "#root.methodName")
    public Map<String, List<Catelog2Vo>> getCatalogJson() {

        System.out.println("----查询了数据库----");
        /**
         * 1、将数据库的多次查询变为一次
         */
        List<CategoryEntity> selectList = this.baseMapper.selectList(new QueryWrapper<>(null));
        // 1、查出所有一级分类
        List<CategoryEntity> level1Categorys = this.getParent_cid(selectList, 0L);
        // 2、封装数据
        Map<String, List<Catelog2Vo>> parent_cid = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), (v) -> {
            // 1、遍历的是所有的一级分类，要查到这个一级分类的二级分类
            List<CategoryEntity> categoryEntities = getParent_cid(selectList, v.getCatId());
            // 2、封装上面的结果
            List<Catelog2Vo> catelog2Vos = null;
            if (categoryEntities != null && categoryEntities.size() > 0) {
                catelog2Vos = categoryEntities.stream().map((l2) -> {
                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                    // 1、找当前二级分类的三级分类封装成vo
                    List<CategoryEntity> level3Catelog = getParent_cid(selectList, l2.getCatId());

                    if (level3Catelog != null && level3Catelog.size() > 0) {
                        List<Catelog2Vo.Catelog3Vo> collect = level3Catelog.stream().map((l3) -> {
                            // 2、封装成指定格式
                            Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                            return catelog3Vo;
                        }).collect(Collectors.toList());

                        catelog2Vo.setCatalog3List(collect);
                    }
                    return catelog2Vo;
                }).collect(Collectors.toList());
            }
            return catelog2Vos;
        }));
        return parent_cid;
    }
}